package com.fyyg.wechat.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.fyyg.common.aliyun.oss.OSSFileUploadUtil;
import com.fyyg.common.util.FileOperationUtil;
import com.fyyg.common.util.date.DateUtil;
import com.fyyg.common.util.date.YXDate;

public class FileUploadServlet extends HttpServlet {

	public FileUploadServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		String uploadType = request.getParameter("uploadType");
		String type = request.getParameter("type");
		String xdfilepath = "imgupload/" + uploadType+ "/" + type + "/";
		System.out.println(xdfilepath+"::xdfilepath");
		
		String ret = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		ret = sdf.format(new Date());
		
		StringBuffer pathname = new StringBuffer(ret);
		String basepath = request.getRealPath(xdfilepath+"/"+pathname);
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (!isMultipart) {
			return;
		}
		String filepath = null;
		try {
			File file = new File(basepath);
			if (!file.exists()) {
				file.mkdirs();
			}
			DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, file);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 设置路径、文件名的字符集
			upload.setHeaderEncoding("UTF-8");
			// 设置允许用户上传文件大小,单位:字节
			upload.setSizeMax(1024 * 1024 * 100);
			// 得到所有的表单域，它们目前都被当作FileItem
			List<FileItem> fileItems = null;
			try {
				fileItems = upload.parseRequest(request);
				// 依次处理请求
				Iterator<FileItem> iter = fileItems.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					if (item.isFormField()) {
						// 如果item是正常的表单域
					} else {
						// 如果item是文件上传表单域
						// 获得文件名及路径
						String fileName = item.getName();
						if (fileName != null && !fileName.equals("")) {
							String newname = FileOperationUtil.getNewName(fileName);
							basepath = basepath  + "\\" + newname;
							File fileOnServer = new File(basepath);
							item.write(fileOnServer);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (Exception e1) {
			e1.printStackTrace();

			throw new IOException(e1.getMessage());
		}
		PrintWriter out = response.getWriter();
		try {
			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			Object object = request.getParameter("htClassName");
			String fileSuffix  = basepath.substring(basepath.lastIndexOf(".")+1,basepath.length());	
			String dirname = YXDate.formateDate(YXDate.getTime()); //文件夹存放位置
			String relativePath =  OSSFileUploadUtil.uploadFile(basepath,dirname+"/"+YXDate.myfromDate1(YXDate.getTime())+new Random(100).nextInt()+ "." + fileSuffix);
			out.print(relativePath);
			out.flush();
			System.out.println(basepath);
		} catch (Exception e) {
			throw new IOException(e.getMessage());
		}
	}

	public void init() throws ServletException {
		// Put your code here
	}

	public String saveFileNew(HttpServletRequest request, final String basepath)
			throws Exception {
//		StringBuffer pathname = new StringBuffer(DateUtil.getPureNumDateTimeStr());
//		String url = basepath +"/"+pathname;
		File file = new File(basepath);
		String pathandname = "";
		if (!file.exists()) {
			file.mkdirs();
		}
		DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, file);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置路径、文件名的字符集
		upload.setHeaderEncoding("UTF-8");
		// 设置允许用户上传文件大小,单位:字节
		upload.setSizeMax(1024 * 1024 * 100);
		// 解析请求，开始读取数据
		// Iterator<FileItem> iter = (Iterator<FileItem>)
		// upload.getItemIterator(request);
		// 得到所有的表单域，它们目前都被当作FileItem
		List<FileItem> fileItems = null;
		try {
			fileItems = upload.parseRequest(request);

			// 依次处理请求
			Iterator<FileItem> iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					// 如果item是正常的表单域

				} else {
					// 如果item是文件上传表单域
					// 获得文件名及路径
					String fileName = item.getName();
					if (fileName != null && !fileName.equals("")) {

						String newname = FileOperationUtil.getNewName(fileName);
						pathandname = basepath  + "/" + newname;
						File fileOnServer = new File(pathandname);
						item.write(fileOnServer);
						pathandname = "/" + newname;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pathandname;
	}
	
	/*public static String getNewName(String name){
		if(name!=null && !"".equals(name)){
			String lastname = name.substring(name.lastIndexOf("."),name.length());
	        StringBuffer  newname = new StringBuffer(DateUtil.getPureNumDateTimeStr());
	        int max=9;
	        int min=0;
	        Random random = new Random();
	        for (int i = 0; i < 6; i++)
			{
	            int rand = random.nextInt(max)%(max-min+1) + min;
	            newname.append(rand);
			}
	        newname.append(lastname);
	        return newname.toString();
		}
		return "";
	}*/
}
